#!/usr/bin/python
#
# wisprclient - WISPr hotspot authentication protocol client
# Copyright (C) 2010  Obey Arthur Liu <arthur@milliways.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


__author__ = 'Obey Arthur Liu <arthur@milliways.fr>'

import BeautifulSoup
import optparse
import re
import urllib


class HotSpot(object):

  def __init__(self, options):
    self.options = options
    self.login_url = ''
    self.logoff_url = ''

  def RequestLogin(self):
    xml_str = urllib.urlopen('http://www.google.com').read()
    xml_str = re.search('(<\s*WISPAccessGatewayParam.*>.*<\s*/\s*WISPAccessGatewayParam\s*>)', xml_str, re.DOTALL).group(0)
    xml = BeautifulSoup.BeautifulSoup(xml_str)
    for child in xml.wispaccessgatewayparam.contents:
      try:
        if child.name == 'redirect':
          self.HandleRedirect(child)
          return
      except AttributeError:
        pass

  def SendLogin(self):
    credentials = urllib.urlencode({
        'button': 'Login',
        'UserName': self.options.provider + '/' + self.options.username,
        'Password': self.options.password,
        'FNAME': '0',
        'OriginatingServer': 'http://www.google.com',
        })
    xml_str = urllib.urlopen(self.login_url, credentials)
    xml = BeautifulSoup.BeautifulSoup(xml_str)
    for child in xml.wispaccessgatewayparam.contents:
      try:
        if child.name == 'authenticationreply':
          self.HandleAuthenticationReply(child)
          return
      except AttributeError:
        pass

  def SendLogoff(self):
    print 'Sent logoff to: ' + self.logoff_url
    urllib.urlopen(self.logoff_url)

  def HandleRedirect(self, tree):
    print 'Hotspot detected: ' + str(tree.accesslocation.string) + ' (' + str(tree.locationname.string) + ')'
    self.login_url = str(tree.loginurl.string)

  def HandleAuthenticationReply(self, tree):
    print 'Login successful.'
    self.logoff_url = str(tree.logoffurl.string)


def main():
  parser = optparse.OptionParser(usage='%prog -u user@domain.com -p pinkunicorns')
  parser.add_option('--provider', default='IPASS')
  parser.add_option('-u', '--username')
  parser.add_option('-p', '--password')
  parser.add_option('-P', '--password_file')
  (options, args) = parser.parse_args()
  if options.password_file:
    options.password = open(options.password_file).read()
  if not options.username:
    parser.error('Username missing')
  hotspot = HotSpot(options)
  hotspot.RequestLogin()
  hotspot.SendLogin()
  raw_input('Press Enter to logoff.\n')
  hotspot.SendLogoff()
 
if __name__ == "__main__":
    main()
